package com.evangelion.web.filter;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;


/**
 * Date: 2/17/14
 */
@WebFilter(
        filterName = "SecurityControlFilter",
        urlPatterns = "/*")
public class SecurityFilter implements Filter {

    //private static Logger logger = LoggerFactory.getLogger(SecurityFilter.class);

    private final String LOGIN_PAGE = "/faces/index.xhtml";

    private final String LOGIN_URL = "/login";

    private final String LOGOUT_URL = "/logout";

    public void init(FilterConfig filterConfig) throws ServletException {
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //logger.debug("Enter Filter");

        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession(true);
        String uri = ((HttpServletRequest) request).getRequestURI();
        String contextPath = ((HttpServletRequest) request).getContextPath();

        if (uri.contains("index.xhtml")) {
            Enumeration<String> pNames = req.getParameterNames();
            if (null != pNames) {
                while (pNames.hasMoreElements()) {
                    String name = pNames.nextElement();
                    System.out.println("name=" + name + ", value=" + req.getParameter(name));
                }
            }
        }


        if(uri.endsWith(".js") || uri.endsWith(".css") || uri.endsWith(".png") || uri.endsWith(".jpg") || uri.endsWith(".ico")) {
            chain.doFilter(request, response);
            return;
        }
        else if (uri.endsWith("/faces/index.xhtml")) {
            chain.doFilter(request, response);
            return;
        }
        else if ((null != SecurityUtils.getUserFromSession(session)) ) {

            if(uri.endsWith(LOGOUT_URL)){
                session.invalidate();
                ((HttpServletResponse) response).sendRedirect(contextPath + LOGIN_PAGE);
                return;
            }

            chain.doFilter(request, response);
            return;
        } else if (uri.endsWith(LOGIN_URL)) {
            if(!login(req, response)) {
                ((HttpServletResponse) response).sendRedirect(contextPath + LOGIN_PAGE);
            }
            else {
                ((HttpServletResponse) response).sendRedirect(contextPath);
            }
            return;
        }
        else {
            ((HttpServletResponse) response).sendRedirect(contextPath + LOGIN_PAGE);
            return;
        }
        //chain.doFilter(request, response);
    }


    private boolean login(HttpServletRequest req, ServletResponse response) throws IOException {
        String contextPath = req.getContextPath();

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //logger.debug("In Filter request.getusername : " + username);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            req.setAttribute("errorMsg", "Please enter Password / Username.");
            return false;
        }

        //AppModelService modelService = FactoryUtil.getFactory().get(AppModelServiceImpl.class);
        //Usuario user = Utils.getEntity(modelService, username, Usuario.class);

//        if (user == null) {
//            req.setAttribute("errorMsg", "User is not found.");
//            return false;
//        }

        //boolean passworkdValid = modelService.checkPassword(user, password);
        //if (!passworkdValid) {
        //    req.setAttribute("errorMsg", "Username / Password is invalid.");
        //    return false;
        //}

        //logger.debug("In Filter : user " + user);
        return true;

    }


    public void destroy() {
    }

}


